package com.ubxtech.i18n.support;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.ubxtech.core.utils.SpringUtils;
import com.ubxtech.core.utils.StrPool;
import com.ubxtech.i18n.properties.CustomI18nProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.StaticMessageSource;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

/**
 * 国际化文件从nacos中拿
 * https://blog.csdn.net/ice24for/article/details/129318633
 * @author Victor.Xiao
 * @since 2023-12-18 15:30
 **/
@Slf4j
public class NacosStaticMessageSource extends StaticMessageSource  {

    private CustomI18nProperties customI18nProperties;
    private NacosConfigProperties nacosConfigProperties;
    private ConfigService configService;
    public NacosStaticMessageSource(CustomI18nProperties customI18nProperties, NacosConfigProperties nacosConfigProperties, ConfigService configService) {
        this.customI18nProperties = customI18nProperties;
        this.nacosConfigProperties = nacosConfigProperties;
        this.configService = configService;
    }
    public void initMessageSource() {

        //加载两次,第一次加载通用配置,第二次加载各自服务自定义配置
        initAppMessageCode(0);
        initAppMessageCode(1);

    }

    /**
     * 要不要去掉appName的拼接,能避免每个服务都要配置 ,1:拼接,0:不拼接
     * @author Victor.Xiao
     * @since 2023-12-18 20:35
     * @param hasApp 1:拼接,0:不拼接
    */
    public void initAppMessageCode(int hasApp) {
        String appName = SpringUtils.getApplicationName();
        String dataId = getDataId(hasApp,appName,customI18nProperties.getSuffixName(),"");
        //加载默认配置
        initMessageCode(dataId, Locale.getDefault());
        //加载其它语言配置
        if (CollectionUtil.isNotEmpty(customI18nProperties.getLanguage())) {
            for (String lang : customI18nProperties.getLanguage()) {

                final String[] locate = lang.split(StrPool.UNDERSCORE);
                dataId = getDataId(hasApp,appName,customI18nProperties.getSuffixName(),lang);
                if (locate.length == 1) {
                    //只有语言的情况
                    initMessageCode(dataId,new Locale(locate[0]));
                } else {
                    initMessageCode(dataId,new Locale(locate[0],locate[1]));
                }
            }
        }
    }

    public void initMessageCode(String dataId,Locale locale) {
        try {
            String configStr = configService.getConfig(dataId, nacosConfigProperties.getGroup(), nacosConfigProperties.getTimeout());
            log.debug("加载nacos国际化配置文件,{}",dataId);
            if (StrUtil.isNotBlank(configStr)) {
                initMessageCodeByConfig(configStr, locale);
            }
            //添加监听配置
            configService.addListener(dataId, nacosConfigProperties.getGroup(), new NacosI18nConfigListener(this,locale));
        } catch (Exception e) {
            log.error("加载nacos国际化配置文件有误,"+dataId,e);
        }
    }

    public void initMessageCodeByConfig(String configStr,Locale locale) {
        try {
            if (StrUtil.isNotBlank(configStr)) {
                Properties properties = new Properties();
                // 加载字符串到Properties对象,必须用InputStreamReader,否则乱码
                properties.load(new InputStreamReader(new ByteArrayInputStream(configStr.getBytes(StandardCharsets.UTF_8))));
                // 输出结果
                for (Map.Entry<Object,Object> entry : properties.entrySet()) {
                    this.addMessage(entry.getKey().toString(),locale,entry.getValue().toString());
                }
            }
        } catch (Exception e) {
            log.error("加载nacos国际化配置文件有误,配置文件:{}",configStr);
            log.error("加载nacos国际化配置文件有误",e);
        }
    }

    public String getDataId(int hasApp ,String appName,String suffix,String lang) {
        if (StrUtil.isBlank(lang)) {
            //不拼接appName
            if (hasApp != 1) {
                return suffix+".properties";
            }
            return appName+"-"+suffix+".properties";
        }
        //不拼接appName
        if (hasApp != 1) {
            return suffix+"-"+lang+".properties";
        }
        return appName+"-"+suffix+"-"+lang+".properties";
    }
}
